package com.example.cloud.service.inventory.impl;

import com.example.cloud.constants.StateConstants;
import com.example.cloud.dao.basic.info.ProductRepository;
import com.example.cloud.dao.inventory.InventoryRepository;
import com.example.cloud.dao.mongdb.basic.info.MongoProductRepository;
import com.example.cloud.model.basic.Product;
import com.example.cloud.model.inventory.Inventory;
import com.example.cloud.model.system.User;
import com.example.cloud.service.inventory.InventoryService;
import com.example.cloud.utils.BusinessUtil;
import com.example.cloud.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

/**
 * Created by wangtao on 2018/8/18.
 */
@Service
public class InventoryServiceImpl implements InventoryService {

    @Autowired
    private InventoryRepository inventoryRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private MongoProductRepository mongoProductRepository;

    @Override
    @Transactional
    public Inventory doSave(Inventory record) {
        // 新增
        if(record.getId() == null){
            User loginUser = RequestUtil.getLoginUser();
            record.setUserId(loginUser.getId());
            record.setAccountId(loginUser.getAccountId());
            record.setOrganId(loginUser.getOrganId());
            record.setOrganName(loginUser.getOrganName());
        }
        BusinessUtil.appendRecord(record);
        record = inventoryRepository.save(record);

        // 更新商品库存标识
        Product product = productRepository.findOne(record.getItemId());
        product.setInventoryFlag(StateConstants.INVENTORY_FLAG_YES);
        BusinessUtil.appendRecord(product);
        productRepository.save(product);
        // 同步缓存
        mongoProductRepository.save(product);
        return record;
    }
}
